import torch.nn as nn
import torch.nn.functional as F
import torch as th
from torch.distributions import Categorical
from torch.nn import LayerNorm
from utils.th_utils import orthogonal_init_


class SepRNNAgent(nn.Module):
    def __init__(self, input_shape, args, id):
        super(SepRNNAgent, self).__init__()
        self.args = args
        self.id = id
        self.rnn_hidden_dim = args.rnn_hidden_dim

        self.fc1 = nn.Linear(input_shape, self.rnn_hidden_dim)
        self.rnn = nn.GRUCell(self.rnn_hidden_dim, self.rnn_hidden_dim)
        self.fc2 = nn.Linear(self.rnn_hidden_dim, args.n_actions)

        if getattr(args, "use_layer_norm", False):
            self.layer_norm = LayerNorm(args.rnn_hidden_dim)
        
        if getattr(args, "use_orthogonal", False):
            orthogonal_init_(self.fc1)
            orthogonal_init_(self.fc2, gain=args.gain)

    def init_hidden(self):
        # make hidden states on same device as model
        return self.fc1.weight.new(1, self.rnn_hidden_dim).zero_()

    def forward(self, x, hidden_state):
        x = F.relu(self.fc1(x), inplace=True)
        # h_in = hidden_state.reshape(-1, self.rnn_hidden_dim)
        h = self.rnn(x, hidden_state)
        if getattr(self.args, "use_layer_norm", False):
            q = self.fc2(self.layer_norm(h))
        else:
            q = self.fc2(h)

        return q, h
